package com.oren.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author wangshiwei
 * @create 2018/7/7 17:06
 * @desc 切面代理
 **/
public  abstract class AspectProxy implements Proxy{

    private  static final Logger LOGGER=LoggerFactory.getLogger(AspectProxy.class);


    public final  Object doProxy(ProxyChain proxyChain)throws Throwable{

        Object result = null;
        //获取目标类
        Class<?> cls=proxyChain.getTargetClass();
        //获取目标方法
        Method method=proxyChain.getTargetMethod();
        //获取目标的参数
        Object[] prams=proxyChain.getMethodParams();

        begin();

        try {
            //是否启动代理
            if(intercept(cls,method,prams)){
                before(cls,method,prams);
                result=proxyChain.doProxyChain();
                after(cls,method,prams,result);
            }else {
                result=proxyChain.doProxyChain();
            }
        }catch (Exception e){
            LOGGER.error("proxy failure",e);
            error(cls,method,prams,e);
            throw  e;
        }finally {
            end();
        }
        return result;
    }

    public void begin(){
    }

    public boolean intercept(Class<?> cls,Method method,Object[] params)throws Throwable{
        return true;
    }

    public void before(Class<?> cls,Method method,Object[] params)throws Throwable{

    }

    public void after(Class<?> cls,Method method,Object[] params,Object result)throws Throwable{

    }

    public void error(Class<?> cls,Method method,Object[] params,Throwable e){

    }

    public void end(){

    }

}
